let initialPoints = 25000
let maxRound = 8

function setGameRound(game, dealer, roundNumber) {
	const wind = TILE_WINDS[Math.floor(roundNumber / playerCount)]
	game.dealer = dealer
	game.roundNumber = roundNumber
	game.round = createRound(`${getTileKanjiText(wind)} ${roundNumber % playerCount + 1} 局 ${game.honba} 本场`, dealer, () => renderGame(game), () => endGameRound(game))

	game.round.dealer = dealer
	game.round.roundWind = wind
	for (let playerId = 0; playerId < playerCount; ++playerId) {
		game.round.players[playerId].seatWind = TILE_WINDS[(playerId - dealer + playerCount) % playerCount]
	}

	console.log('Start round', game.round.name)
	playPhase(game.round)
}
function advanceGameRound(game) {
	const progress = game.round.progress
	if (progress) {
		// Check ending condition
		let ended = (game.roundNumber + 1 >= maxRound)
		for (let playerId = 0; playerId < playerCount; ++playerId) {
			if (game.points[playerId] < 0) {
				ended = true
				break
			}
		}
		if (ended) {
			// Game ends
			game.ended = true
			renderGame(game)
		} else {
			// Game continues
			game.honba = 0
			setGameRound(game, (game.dealer + 1) % playerCount, game.roundNumber + 1)
		}
	} else {
		++game.honba
		setGameRound(game, game.dealer, game.roundNumber)
	}
}
function endGameRound(game) {
	// Update points
	for (let playerId = 0; playerId < playerCount; ++playerId) {
		game.points[playerId] += game.round.players[playerId].gain - game.round.players[playerId].loss
	}
}
let currentGame = {}
function createGame() {
	// Initial points are all zero
	currentGame = {
		points: new Array(playerCount).fill(initialPoints),
		dealer: 0,
		honba: 0,
	}
	setGameRound(currentGame, 0, 0)
}
function renderGame(game) {
	clearElements()
	addGameElement(game)
}
function loadConfig() {
	playerCount = getConfig('players')
	if (getConfig('playAsRandom')) {
		const play = Math.floor(Math.random() * playerCount)
		playing = new Array(playerCount).fill(false).map((_, i) => (i === play))
	} else {
		playing = new Array(playerCount).fill(false).map((_, i) => (!getConfig('ai' + i)))
	}
	aiDepth = getConfig('aiHard') ? 1 : 0
	initialPoints = getConfig('initial')
	maxRound = getConfig('maxRound')
	initialDora = getConfig('initialDora')
	maxDora = getConfig('maxDora')
	maxKan = getConfig('maxKan')
	concealTiles = Math.max(getConfig('conceal'), maxDora * 2 + maxKan)
	maxHu = getConfig('maxHu')

	pinfuRequiresNoFu = getConfig('pinfuRequiresNoFu')
	pinfuRequires3Waits = getConfig('pinfuRequires3Waits')
	pinfuRequiresNoDora = getConfig('pinfuRequiresNoDora')

	let aka = getConfig('aka')
	akaCount = [Math.floor(aka / 3), Math.floor((aka + 2) / 3), Math.floor((aka + 1) / 3), 0]
}
function initialize() {
	loadConfig()
	createGame()
	showMainContainer()
}